package com.iyunsir.lesson02_tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemo02 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            // 1.我得到有一个地址

            serverSocket = new ServerSocket(9999);
            // 2.等待客户端连接
            socket = serverSocket.accept();
            // 3.读取消息
            is = socket.getInputStream();

            // 4. 文件传输
            FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));

            // 5. 管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
            // 通知客户端我接收完毕了
            try (OutputStream os = socket.getOutputStream()){
            os.write("我接收完毕了,你可以端开了".getBytes());}
            // System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
